package com.xuxiao.springbootexp03.Dao;

import com.xuxiao.springbootexp03.Configuration.ConfigBean;
import com.xuxiao.springbootexp03.Entity.Region;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Repository
public class RegionPropertiesDao implements InitializingBean {
    //存放数据的列表
    private List<Region> regionList=null;

    @Autowired
    private ConfigBean configBean;

    private Resource getResource(){
        //请求路径
        URI uri=URI.create(configBean.getCORONA_VIRUS_DATA_URL());
        //请求实体
        RequestEntity<Void> requestEntity= RequestEntity
                .get(uri)
                .headers(httpHeaders -> httpHeaders.add("User-Agent",configBean.getUser_Agent()))
                .build();
        //响应实体
        ResponseEntity<Resource> responseEntity=new RestTemplate()
                .exchange(requestEntity,Resource.class);
        return responseEntity.getBody();
    }

    private void getAllProperties() throws IOException {
        //拉取数据
        Resource  resource=getResource();

        //读取csv中的数据
        assert resource != null;
        Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
        Iterable<CSVRecord> records= CSVFormat.RFC4180.withHeader("Province/State","Country/Region","Lat","Long").parse(reader);

        regionList=new ArrayList<Region>();

        for(CSVRecord record:records){
            Region region=new Region();
            List<String> dataList=new ArrayList<String>();

            region.setProvince(record.get("Province/State"));
            region.setCountry(record.get("Country/Region"));
            region.setLatitude(record.get("Lat"));
            region.setLongitude(record.get("Long"));
            region.setLatestData(record.get(record.size()-1));
            for(int i=4;i<record.size()-1;++i){
                dataList.add(record.get(i));
            }
            region.setDataList(dataList);

            regionList.add(region);
        }


    }

    public List<Region> getRegionList() throws IOException {
        if(regionList==null){
            getAllProperties();
        }
        return regionList;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        getAllProperties();
    }

    @Scheduled(cron = "${resource.Cron}")
    private void updateDate() throws IOException {
        Logger logger= LoggerFactory.getLogger(RegionPropertiesDao.class);
        logger.info("Scheduled Update Corona Virus Data in "+ LocalDateTime.now());
        getAllProperties();
    }
}
